package com.sh.d1.gameserver;

import com.google.protobuf.GeneratedMessageV3;
import com.sh.d1.gameserver.cmdhandler.MyCmdHandlerContext;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.util.AttributeKey;
import com.sh.util.LoadStatistic;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 自定义的二进制数据处理器
 */
public class GameMsgHandler extends SimpleChannelInboundHandler<Object> {
    /**
     * 日志对象
     */
    static private final Logger LOGGER = LoggerFactory.getLogger(GameMsgHandler.class);

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        LOGGER.info("有网关服务器连入");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        LOGGER.info("有网关服务器断开");

        Broadcaster.removeChannel(ctx.channel());

        Integer gatewayServerId = ctx.channel().attr(AttributeKey.<Integer>valueOf("gatewayServerId")).get();
        if (null != gatewayServerId) {
            LoadStatistic.removeGatewayServerId(gatewayServerId);
        }
    }

    @Override
    protected void channelRead0(ChannelHandlerContext nettyCtx, Object msgObj) {
        LOGGER.debug(
                "收到客户端数据, msgType = {}",
                msgObj.getClass().getName()
        );

        if (msgObj instanceof InternalServerMsg) {
            // 转成内部服务器消息
            InternalServerMsg innerMsg = (InternalServerMsg) msgObj;

            Broadcaster.addChannel(
                    innerMsg.getGatewayServerId(),
                    innerMsg.getRemoteSessionId(),
                    nettyCtx.channel()
            );
            nettyCtx.channel().attr(AttributeKey.<Integer>valueOf("gatewayServerId"))
                    .setIfAbsent(innerMsg.getGatewayServerId());

            MyCmdHandlerContext myCtx = new MyCmdHandlerContext(
                    nettyCtx,
                    innerMsg.getGatewayServerId(),
                    innerMsg.getRemoteSessionId(),
                    innerMsg.getFromUserId()
            );

            // 处理消息对象
            MainThreadProcessor.getInstance().process(
                    myCtx, (GeneratedMessageV3) innerMsg.getMsgObj()
            );
        }

    }


    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object event) throws Exception {
        if (null == ctx ||
                null == event) {
            return;
        }
        if (event instanceof WebSocketServerProtocolHandler.HandshakeComplete) {
            HttpHeaders httpHeaders = ((WebSocketServerProtocolHandler.HandshakeComplete) event).requestHeaders();
            String gatewayServerId = httpHeaders.get("gatewayServerId");
            LOGGER.info("网关服务器连入! gatewayServerId ={}",
                    gatewayServerId);
            ctx.channel().attr(AttributeKey.<Integer>valueOf("gatewayServerId"))
                    .setIfAbsent(Integer.parseInt(gatewayServerId));
        }
    }
}
